/*
公共函数
 */

import axios from 'axios'
import Layer from './layer.js'
import electron from 'electron'
import path from 'path'
import qs from 'qs'

const ISDEV = process.env.NODE_ENV === 'development' ? 1 : 0

class C {
  constructor () {
  }
  /*
   * 设置缓存
   */
  setLocalStorage (name, data) {
    data ? localStorage.setItem(name, JSON.stringify(data)) : localStorage.removeItem(name)
  }

  /*
   * 获取缓存
   * 支持二级获取
   */
  getLocalStorage (name) {
    name = name.split('.')
    // 获取数据
    let data = JSON.parse(localStorage.getItem(name[0]))
    return name[1] ? data[name[1]] : data
  }

  /*
   * 判断是否在数组中存在
   * @author: huang
   * 支持多个属性判断
   */
  inarray (obj, array) {
    let key = -1
    array.forEach((row, index) => {
      let ishave = true
      for (let i in obj) {
        if (row[i] !== obj[i]) {
          ishave = false
        }
      }
      if (ishave) key = index
    })
    return key
  }

  /*
   * 关闭窗口
   * @author: 黄
   */
  closewin () {
    const electron = require('electron')
    const win = electron.remote.getCurrentWindow()
    win.close()
  }

  /*
   * 防止重复点击
   */
  openLoading (url) {
    let loadUrl = 'loading' + url
    let setTime = 'settime' + url
    // 默认延时1秒自动关闭(开启此功能表示只要数据请求不成功那么在1秒内是不允许再次请求的)
    if (!this[setTime]) {
      this[setTime] = setTimeout(() => {
        delete this[loadUrl]
        delete this[setTime]
      }, 1000)
    }
    if (this[loadUrl]) return false
    this[loadUrl] = true
    return true
  }

  closeLoading (url) {
    let loadUrl = 'loading' + url
    let setTime = 'settime' + url
    delete this[loadUrl]
    clearTimeout(this[setTime])
    delete this[setTime]
  }

  /*
   * 简单对象深拷贝
   * 注：不能拷贝函数
   */
  copy (obj) {
    return JSON.parse(JSON.stringify(obj))
  }
  /*
   * 简单继承函数
   */
  assign (objA, objB) {
    return Object.assign({}, objA, objB)
  }

  /*
   * 较复杂的深拷贝（可拷贝函数）
   */
  deepCopy (obj) {}


  /** *******************新式页面弹窗及传参*********************/
  openBrowserWindow (url, option) {
    let that = this
    option = Object.assign({refresh: false, winname: url, data: {}, option: {}}, option || {}) // 组合选项（refresh刷新，winname：窗口名称）
    // 定义常量
    const BrowserWindow = electron.remote.BrowserWindow
    let newurl = process.env.NODE_ENV === 'development'
      ? 'http://localhost:9080/'
      : path.join('file://', __dirname, '/index.html')
    newurl = newurl + '#' + url
    return new Promise((resolve, reject) => {
      // 查询窗口是否打开
      let winlist = this.getLocalStorage('winlist') || {}
      if (winlist && winlist[option.winname]) {
        let win = BrowserWindow.fromId(winlist[option.winname])
        if (win) {
          let oldurl = win.webContents.getURL()
          if (oldurl !== newurl && option.refresh) {
            // 跳转新地址（暂时后期可以用监听）
            win.webContents.send('H_changeurl', {
              newurl: url,
              winid: winlist[option.winname]
            })
          }
          win.show()
        } else {
          delete winlist[option.winname]
          this.setLocalStorage('winlist', winlist)
          this.openBrowserWindow(url, option)
        }
      } else {
        if (ISDEV) option.option.webPreferences = {webSecurity: false}
        let win = new BrowserWindow(option.option)
        // win.webContents.openDevTools()
        let sendId = 'send_' + win.id
        let receiveId = 'receive_' + win.id

        // 设置传参
        that.setLocalStorage(sendId, option.data)

        // win.setResizable(false)
        winlist[option.winname] = win.id
        this.setLocalStorage('winlist', winlist)
        win.on('closed', function () {
          let ws = that.getLocalStorage('winlist')
          delete ws[option.winname]
          that.setLocalStorage('winlist', ws)
          let receiveData = that.getLocalStorage(receiveId)
          resolve(receiveData)
          that.setLocalStorage(sendId)
          that.setLocalStorage(receiveId)
          // that.electron.ipcRenderer.removeAllListeners('H_changestore')
          win = null
        })
        win.on('resize', () => {
          const [width, height] = win.getContentSize()
          for (let wc of electron.remote.webContents.getAllWebContents()) {
            // Check if `wc` belongs to a webview in the `win` window.
            if (wc.hostWebContents &&
              wc.hostWebContents.id === win.webContents.id) {
              wc.setSize({
                normal: {
                  width: width,
                  height: height
                }
              })
            }
          }
        })
        win.loadURL(newurl)
        // win.show()
      }
    }).catch((e) => {
      console.log(e)
      Layer.error('未知错误！')
    })
  }
  closeBrowserWindow (data, win) {
    win = !win ? electron.remote.getCurrentWindow() : win
    data = data || {}
    this.setLocalStorage('receive_' + win.id, data)
    win.close()
  }
  getDatas () {
    let win = electron.remote.getCurrentWindow()
    return this.getLocalStorage('send_' + win.id)
  }
  /** *******************新式页面弹窗及传参*********************/
  
  /*
   * 重构ajax请求
   * 只输出成功数据，错误数据在此屏蔽或统一提示
   * 考虑加入防止重复点击
   * url:string,data:json,option:json
   * output: data
   */
  async _ajax (url, data, type, option) {
    // 首先进行基础配置
    type = type || 'get'
    let opt = type === 'get' ? {params: data} : {data: qs.stringify(data)}
    opt = Object.assign(opt, {
      url: url,
      method: type,
      baseURL: this.Conf.domain
    }, option)
    // 暂时用自己写的防止重复点击
    if (!this.openLoading(url)) return false
    // Layer.openLoading() 暂时不用elementui的loading，用的时候开启即可
    let res = await axios(opt)
    // Layer.closeLoading()
    this.closeLoading(url)
    // 暂时只允许200请求，其他的先报网络错误
    return res.status === 200 ? res.data : Layer.error('网络错误，请稍候再试！')
  }

  /** **************以上为通用，以下为本项目使用****************/

  /*
   * 成功提示
   */
  success (str) {
    Layer.success(str)
  }

  /*
   * 错误提示
   */
  error (str) {
    Layer.error(str)
  }

  /*
   * 提示框
   */
  confirm (str, fun) {
    Layer.confirm(str, fun)
  }

  /*
   * prompt
   */
  prompt (tips, fun) {
    Layer.prompt(tips, fun)
  }

  /*
   * 制作通用ajax传输
   * 作用带自动过滤错误提示，（thinkjs的错误提示）
   * 带token验证方式
   */
  async ajax (url, data, type, option) {
    // 发送请求前对比机器码是否正确（如果有token对比，没有就忽略）
    let res = await this._ajax(url, data, type, option)
    console.log(res)
    // thinkjs通用过滤
    if (res.errno > 0) {
      if (res.errno === 1000) {
        Layer.error(res.errmsg)
        return false
      } else {
        Layer.error('未知错误！')
        return false
      }
    } else {
      return res
    }
  }

  /*
   * 页内弹窗
   * 临时使用
   */
  openDialog (store, currentView, data, width) {
    return Layer.openDialog(store, currentView, data, width)
  }

  /*
   * 关闭页内弹窗
   */
  closeDialog (obj, data) {
    Layer.closeDialog(obj, data)
  }

  /*
   * 获取页内弹窗数据
   */
  gets (obj) {
    return Layer.gets(obj)
  }
}

export default new C()
